<template>
  <div class="profile-page">
    <!-- 顶部导航栏 -->
    <Navbar />

    <div class="container">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="profile-content" v-loading="loading">
        <div v-if="!loading && userInfo" class="profile-layout">
          <!-- 左侧：用户信息卡片 -->
          <div class="user-card">
            <div class="avatar-section">
              <img :src="getAvatarUrl(userInfo.avatar)" class="avatar" />
              <el-button size="small" @click="showAvatarUpload = true">
                <el-icon><Camera /></el-icon>
                更换头像
              </el-button>
            </div>

            <div class="user-basic-info">
              <h2 class="user-name">{{ userInfo.name }}</h2>
              <div class="user-meta">
                <div class="meta-item">
                  <span class="label">学号：</span>
                  <span class="value">{{ userInfo.sno }}</span>
                </div>
                <div class="meta-item">
                  <span class="label">性别：</span>
                  <span class="value">{{ userInfo.sex === 0 ? '男' : '女' }}</span>
                </div>
                <div class="meta-item">
                  <span class="label">VIP等级：</span>
                  <el-tag :type="getVipType(userInfo.vipLevel)">VIP{{ userInfo.vipLevel }}</el-tag>
                </div>
              </div>
            </div>

            <el-button type="danger" plain class="logout-btn" @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-button>
          </div>

          <!-- 右侧：详细信息 -->
          <div class="info-card">
            <el-tabs v-model="activeTab">
              <!-- 基本信息 -->
              <el-tab-pane label="基本信息" name="basic">
                <el-form
                  ref="profileFormRef"
                  :model="profileForm"
                  :rules="profileRules"
                  label-width="100px"
                  class="profile-form"
                >
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="profileForm.name" placeholder="请输入姓名" />
                  </el-form-item>

                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="profileForm.sex">
                      <el-radio :label="0">男</el-radio>
                      <el-radio :label="1">女</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="生日" prop="birthday">
                    <el-date-picker
                      v-model="profileForm.birthday"
                      type="date"
                      placeholder="选择日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                    />
                  </el-form-item>

                  <el-form-item label="地址" prop="address">
                    <el-input
                      v-model="profileForm.address"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入地址"
                    />
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" :loading="saving" @click="handleUpdate">
                      保存修改
                    </el-button>
                    <el-button @click="loadUserProfile">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <!-- 账户信息 -->
              <el-tab-pane label="账户信息" name="account">
                <div class="account-info">
                  <div class="info-row">
                    <span class="label">学号：</span>
                    <span class="value">{{ userInfo.sno }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">VIP等级：</span>
                    <span class="value">VIP{{ userInfo.vipLevel }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">注册时间：</span>
                    <span class="value">{{ userInfo.createTime }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">账户状态：</span>
                    <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
                      {{ userInfo.status === 1 ? '正常' : '停用' }}
                    </el-tag>
                  </div>
                  
                  <el-divider />
                  
                  <div class="password-section">
                    <h3>密码管理</h3>
                    <p class="tip">定期修改密码可以提高账户安全性</p>
                    <el-button type="primary" @click="showChangePasswordDialog = true">
                      <el-icon><Lock /></el-icon>
                      修改密码
                    </el-button>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="showAvatarUpload" title="更换头像" width="400px">
      <ImageUpload
        v-model="avatarPath"
        prefix="user"
        :max-size="2"
        @success="handleAvatarSuccess"
      />
      <template #footer>
        <el-button @click="showAvatarUpload = false">取消</el-button>
        <el-button type="primary" @click="updateAvatar">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <ChangePasswordDialog v-model="showChangePasswordDialog" @success="handlePasswordChanged" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { updateProfile } from '@/api/user'
import { getFileUrl } from '@/api/file'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera, SwitchButton, Lock } from '@element-plus/icons-vue'
import Navbar from '@/components/Navbar.vue'
import ImageUpload from '@/components/ImageUpload.vue'
import ChangePasswordDialog from '@/components/ChangePasswordDialog.vue'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const saving = ref(false)
const activeTab = ref('basic')
const showAvatarUpload = ref(false)
const showChangePasswordDialog = ref(false)
const avatarPath = ref('')

const userInfo = ref(null)
const profileFormRef = ref(null)

const profileForm = reactive({
  name: '',
  sex: 0,
  birthday: '',
  address: ''
})

const profileRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ]
}

// 获取头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar) {
    return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  }
  return getFileUrl(avatar)
}

// VIP等级标签类型
const getVipType = (level) => {
  if (level >= 3) return 'danger'
  if (level >= 2) return 'warning'
  return 'info'
}

// 加载用户信息
const loadUserProfile = async () => {
  loading.value = true
  try {
    const info = await userStore.getUserInfo()
    if (info) {
      userInfo.value = info
      // 填充表单
      profileForm.name = info.name || ''
      profileForm.sex = info.sex || 0
      profileForm.birthday = info.birthday || ''
      profileForm.address = info.address || ''
      avatarPath.value = info.avatar || ''
    } else {
      ElMessage.error('获取用户信息失败')
      router.push('/login')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 更新用户信息
const handleUpdate = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        await updateProfile(profileForm)
        ElMessage.success('保存成功')
        // 重新加载用户信息
        await loadUserProfile()
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请重试')
      } finally {
        saving.value = false
      }
    }
  })
}

// 头像上传成功
const handleAvatarSuccess = (filePath) => {
  avatarPath.value = filePath
}

// 更新头像
const updateAvatar = async () => {
  if (!avatarPath.value) {
    ElMessage.warning('请先上传头像')
    return
  }

  try {
    await updateProfile({ avatar: avatarPath.value })
    ElMessage.success('头像更新成功')
    showAvatarUpload.value = false
    await loadUserProfile()
  } catch (error) {
    console.error('头像更新失败:', error)
    ElMessage.error('头像更新失败')
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/')
  } catch {
    // 取消退出
  }
}

// 修改密码成功
const handlePasswordChanged = () => {
  ElMessage.success('密码修改成功，请重新登录')
  userStore.logout()
  router.push('/')
}

onMounted(() => {
  // 检查是否登录
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/')
    return
  }
  loadUserProfile()
})
</script>

<style scoped>
.profile-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding-top: 20px;
}

.profile-content {
  min-height: 500px;
}

.profile-layout {
  display: grid;
  grid-template-columns: 320px 1fr;
  gap: 20px;
}

/* 左侧用户卡片 */
.user-card {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  text-align: center;
}

.avatar-section {
  margin-bottom: 20px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 15px;
  border: 3px solid #f0f0f0;
}

.user-basic-info {
  margin-bottom: 30px;
}

.user-name {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 20px 0;
}

.user-meta {
  text-align: left;
}

.meta-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.meta-item .label {
  color: #999;
  font-size: 14px;
}

.meta-item .value {
  color: #333;
  font-weight: 500;
}

.logout-btn {
  width: 100%;
}

/* 右侧信息卡片 */
.info-card {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.profile-form {
  max-width: 600px;
}

.account-info {
  max-width: 600px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-row .label {
  color: #666;
  font-weight: 500;
}

.info-row .value {
  color: #333;
}

.password-section {
  margin-top: 30px;
}

.password-section h3 {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.password-section .tip {
  font-size: 14px;
  color: #999;
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .profile-layout {
    grid-template-columns: 1fr;
  }

  .user-card {
    padding: 20px;
  }

  .info-card {
    padding: 20px;
  }
}
</style>
